<template>
  <div class="">
    <span class="logout" @click="logout">注销</span>
    <img src="../assets/logo.png">
    <el-row class="content">
      <el-col :xs="{span:20,offset:2}" :sm="{span:8,offset:8}">
        <span>
          欢迎：{{userName}}！以下是您的 Address Book：
        </span>
        <br/>
        <el-button class="add" type="primary" icon="plus" @click="show">添加</el-button>
        <el-col :xs="24">
          <template v-if="this.list.length > 0">
            <template v-for="(item, index) in list">
              <div class="list" v-if="item.status == false">
                <span class="item">
                  {{ index + 1 }}. <span class="contact">{{ item.contact }}</span>  <span class="mobile">{{ item.mobile }}</span>
                </span>;
                <br/>
                <span class="item">
                  <span class="address">
                    {{ item.address }}
                  </span>
                </span>
                <span class="pull-right">
                  <el-button size="small" type="primary" icon="edit" @click="showUpdate(item.id)"></el-button>
                  <el-button size="small" type="danger" icon="delete" @click="remove(item.id)"></el-button>
                </span>
              </div>
            </template>
          </template>
          <div v-else>
            暂无数据
          </div>
        </el-col>
      </el-col>
    </el-row>
    <el-dialog title="Address" :visible.sync="showEdit">
      <el-form :model="form" :rules="rules">
        <el-form-item label="姓名" label-width="120" prop="contact">
          <el-input v-model="form.contact" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="120" prop="mobile">
          <el-input v-model="form.mobile" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" label-width="120">
          <el-input v-model="form.address" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancle">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import jwt from 'jsonwebtoken';
const ORIGIN_ADDRESS = {
  contact: '',
  mobile: '',
  address: '',
  userId: '',
  status: 0,
};

export default {
  data () {
    return {
      userName: '',
      activeName: 'first',
      list:[],
      count: 0,
      userId: '',
      showEdit: false,
      form: {
        ...ORIGIN_ADDRESS,
      },
      rules: {
        contact: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'change' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
        ],
      },
    };
  },
  methods: {
    logout() {
      sessionStorage.setItem('token',null);
      this.$router.push({ name: 'Login' });
    },
    show() {
      this.showEdit = true;
    },
    cancle() {
      this.showEdit = false;
      this.form = ORIGIN_ADDRESS;
    },
    save() {
      if (this.form.id) {
        this.update();
      } else {
        this.add();
      }
    },
    add() {
      if (!this.form.contact || this.form.mobile.length !== 11) {
        return;
      }
      const data = JSON.parse(JSON.stringify(this.form));
      data.userId = this.userId;

      this.$http.post('/api/addresses', data)
        .then((res) => {
          console.log(res);
          if(res.status == 200 && res.data.status == 0){
            this.$message({
              type: 'success',
              message: '创建成功！'
            });
            this.getAddressBookList();
          }else{
            this.$message.error('创建失败！');
          }
        }, (err) => {
          this.$message.error('创建失败！');
        }).then(() => {
          this.cancle();
        });
    },
    showUpdate(id) {
      const item = this.list.find((element) => {
        return element.id == id;
      });

      if (item === null) {
        this.form = ORIGIN_ADDRESS;
      } else {
        this.form = JSON.parse(JSON.stringify(item));
      }
      this.show();
    },
    update() {
      if (!this.form.id) {
        return;
      }
      const data = JSON.parse(JSON.stringify(this.form));

      this.$http.put(`/api/addresses/${this.form.id}`, data)
        .then((res) => {
          if(res.status == 200 && res.data.status == 0){
            this.$message({
              type: 'success',
              message: '更新成功！'
            })
            this.getAddressBookList();
          }else{
            this.$message.error('更新失败！')
          }
        }, (err) => {
          this.$message.error('更新失败！')
          console.log(err);
        }).then(() => {
          this.cancle();
        });
    },
    remove(id) {
      if (!id) {
        return;
      };
      this.$http.delete(`/api/addresses/${id}`)
        .then((res) => {
          if(res.status == 200 && res.data.status == 0){
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.getAddressBookList();
          }else{
            this.$message.error('删除失败！');
          }
        }, (err) => {
          this.$message.error('删除失败！');
          console.log(err);
        })
    },
    getUserInfo(){
      const token = sessionStorage.getItem('token');
      if(token != null && token != 'null'){
        let decode = jwt.verify(token,'vue-koa-demo');
        return decode;
      }else {
        return null;
      }
    },
    getAddressBookList(){
      this.$http.get(`/api/${this.userId}/addresses/`)
        .then((res) => {
          if(res.status == 200 && res.data.status == 0){
            this.list = res.data.data;
          }else{
            this.$message.error('获取列表失败！');
          }
        }, (err) => {
          this.$message.error('获取列表失败！');
          console.log(err);
        })
    },
  },
  created(){
    const userInfo = this.getUserInfo();
    if(userInfo != null){
      this.userId = userInfo.id;
      this.userName = userInfo.userName;
    }else{
      this.userId = '';
      this.userName = ''
    }
    this.getAddressBookList();
  },
};
</script>

<style lang="stylus" scoped>
  .logout
    position absolute
    top 10px
    right 30px
    font-size 12px
    &:hover
      color #20a0ff
  .add
    width 100%
    margin-top 12px
    margin-bottom 12px
  .list
    width 100%
    margin-top 8px
    padding-bottom 8px
    border-bottom 1px solid #eee
    overflow hidden
    text-align left
    .item
      font-size 20px
      &.finished
        text-decoration line-through
        color #999
      .mobile
        font-size 16px
      .address
        color #999
        font-size 16px
  .pull-right
    float right
  .el-dialog
    @media screen and (min-width: 600px)
      width 100%
</style>
